import { defineStore } from 'pinia'
import { login, register, logout, getUserInfo } from '@/api/user'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    userInfo: null
  }),

  actions: {
    async login(loginData) {
      try {
        const res = await login(loginData)
        this.token = res.data.token
        localStorage.setItem('token', res.data.token)
        return res
      } catch (error) {
        throw error
      }
    },

    async register(registerData) {
      try {
        const res = await register(registerData)
        return res
      } catch (error) {
        throw error
      }
    },

    async getUserInfo() {
      try {
        const res = await getUserInfo()
        this.userInfo = res.data
        return res
      } catch (error) {
        throw error
      }
    },

    async logout() {
      try {
        // 即使后端API调用失败也要清除本地存储
        try {
          await logout();
        } catch (error) {
          console.error('后端登出API调用失败:', error);
        }
        
        // 清除store中的状态
        this.token = '';
        this.userInfo = null;
        
        // 清除localStorage中的所有用户相关信息
        localStorage.removeItem('token');
        localStorage.removeItem('teacherId');
        localStorage.removeItem('teacherName');
        localStorage.removeItem('studentId');
        localStorage.removeItem('studentName');
        localStorage.removeItem('userRole');
        localStorage.removeItem('tokenExpireTime');
        
        return { success: true, message: '退出成功' };
      } catch (error) {
        console.error('退出失败:', error);
        return { success: false, message: '退出失败' };
      }
    }
  }
}) 